import axios from 'axios'; // ✅ 自动解构 default
import fs from 'fs';
import path from 'path';
import os from 'os';
import logger from './logger';

// 存储所有下载任务
const downloadTasks = new Map();
/**
 * 创建并启动一个下载任务
 * @param {string} id - 下载任务唯一ID
 * @param {string} url - 文件URL
 * @param {string} savePath - 本地保存路径（可选）
 * @param {BrowserWindow} mainWindow - Electron 主窗口，用于发送事件
 * @returns {Promise<{ success: boolean, savePath?: string, error?: string }>}
 */
// ✅ 使用 import 后，axios.head 可以直接用！
/**
 * 创建并启动一个下载任务
 * @param {string} id - 下载任务唯一ID
 * @param {string} url - 文件URL
 * @param {string} softName - 文件名称
 * @param {string} savePath - 本地保存路径（可选）
 * @param {BrowserWindow} mainWindow - Electron 主窗口，用于发送事件
 * @returns {Promise<{ success: boolean, savePath?: string, error?: string }>}
 */
export async function createDownload(id, url, softName, savePath, mainWindow) {
  logger.info(`createDownload 开始: id=${id}, url=${url}, savePath=${savePath}`);
  
  if (downloadTasks.has(id)) {
    logger.warn(`下载任务已存在: id=${id}`);
    return { success: false, error: '任务已存在' };
  }
  
  try {
    const filename = decodeURIComponent(url.split('/').pop().split('?')[0]) || 'download.bin';
    const defaultPath = path.join(os.homedir(), 'Downloads', filename);
    savePath = savePath || defaultPath;

    logger.info(`下载路径: ${savePath}`);
    
    const dir = path.dirname(savePath);
    if (!fs.existsSync(dir)) {
      logger.info(`创建目录: ${dir}`);
      fs.mkdirSync(dir, { recursive: true });
    }

    const task = {
      id,
      url,
      softName,
      savePath,
      state: 'progress',
      receivedBytes: 0,
      totalBytes: 0,
      speed: 0,
      percentage: 0,
      lastBytes: 0,
      speedInterval: null,
      writer: null,
      response: null,
    };

    logger.info('发送下载开始事件');
    await mainWindow.webContents.send('download:start', { ...task });

    // 尝试发送 HEAD 请求获取文件信息
    let headResponse;
    let contentLength = 0;
    let acceptRanges = false;
    
    try {
      logger.info('发送 HEAD 请求');
      headResponse = await axios.head(url);
      contentLength = parseInt(headResponse.headers['content-length'], 10) || 0;
      acceptRanges = headResponse.headers['accept-ranges'] === 'bytes';
      logger.info(`HEAD响应: contentLength=${contentLength}, acceptRanges=${acceptRanges}`);
    } catch (headError) {
      logger.warn(`HEAD 请求失败: ${headError.message}`);
    }

    task.totalBytes = contentLength;

    // 检查是否已存在部分下载的文件
    let startByte = 0;
    if (fs.existsSync(savePath)) {
      try {
        const stats = fs.statSync(savePath);
        logger.info(`文件已存在，大小: ${stats.size} bytes`);
        if (acceptRanges && stats.size > 0 && stats.size < contentLength) {
          startByte = stats.size;
          task.receivedBytes = startByte;
          task.lastBytes = startByte;
          logger.info(`断点续传从 ${startByte} 字节开始`);
        } else if (stats.size >= contentLength && contentLength > 0) {
          logger.info('文件已下载完成');
          task.state = 'completed';
          task.percentage = 100;
          mainWindow.webContents.send('download:complete', { 
            id,
            size: stats.size
          });
          return { success: true, savePath };
        } else {
          logger.info('删除不完整文件重新下载');
          fs.unlinkSync(savePath);
        }
      } catch (statError) {
        logger.warn(`检查文件状态失败: ${statError.message}`);
      }
    }

    const config = {
      method: 'GET',
      url,
      responseType: 'stream',
      headers: {},
    };

    if (acceptRanges && startByte > 0) {
      config.headers['Range'] = `bytes=${startByte}-`;
      logger.info(`设置 Range 头: ${config.headers['Range']}`);
    }

    logger.info('发送 GET 请求');
    const response = await axios(config);
    task.response = response;

    // 如果 HEAD 请求没有获取到 contentLength，从 GET 响应中获取
    if (!contentLength) {
      contentLength = parseInt(response.headers['content-length'], 10) || 0;
      task.totalBytes = contentLength;
      logger.info(`从 GET 响应获取 contentLength: ${contentLength}`);
    }

    const writer = fs.createWriteStream(savePath, {
      flags: startByte > 0 ? 'a' : 'w'
    });
    task.writer = writer;

    logger.info('开始接收数据流');
    response.data.on('data', (chunk) => {
      if (task.state !== 'progress') return;
      task.receivedBytes += chunk.length;
      const total = task.totalBytes || contentLength || 0;
      task.percentage = total ? Math.round((task.receivedBytes / total) * 100) : 0;

      // 每10%发送一次进度更新，避免过于频繁
      if (task.percentage % 10 === 0 || task.receivedBytes === total) {
        mainWindow.webContents.send('download:progress', {
          id,
          receivedBytes: task.receivedBytes,
          totalBytes: task.totalBytes,
          percentage: task.percentage
        });
      }
    });

    task.speedInterval = setInterval(() => {
      const diff = task.receivedBytes - task.lastBytes;
      task.lastBytes = task.receivedBytes;
      task.speed = diff;
      mainWindow.webContents.send('download:speed', { id, speed: diff });
    }, 1000);

    response.data.pipe(writer);

    writer.on('finish', () => {
      logger.info('文件写入完成');
      if (task.state === 'progress') {
        task.state = 'completed';
        mainWindow.webContents.send('download:complete', { id });
      }
      cleanupTask(id);
    });

    writer.on('error', (err) => {
      logger.error(`写入文件错误: ${err.message}`);
      task.state = 'error';
      mainWindow.webContents.send('download:error', { id, error: `写入文件失败: ${err.message}` });
      cleanupTask(id);
    });

    response.data.on('error', (err) => {
      logger.error(`下载数据错误: ${err.message}`);
      task.state = 'error';
      mainWindow.webContents.send('download:error', { id, error: `下载失败: ${err.message}` });
      cleanupTask(id);
    });

    downloadTasks.set(id, task);
    logger.info('下载任务创建成功');

    return { success: true, savePath };
  } catch (err) {
    logger.error(`下载失败: ${url}`, err);
    mainWindow.webContents.send('download:error', { id, error: `下载失败: ${err.message}` });
    cleanupTask(id);
    return { success: false, error: err.message };
  }
}

// 清理任务资源
function cleanupTask(id) {
  logger.info(`清理任务资源: id=${id}`);
  const task = downloadTasks.get(id);
  if (!task) return;

  if (task.speedInterval) {
    clearInterval(task.speedInterval);
  }
  if (task.writer) {
    try {
      task.writer.destroy();
    } catch (e) {
      logger.warn(`关闭写入流失败: ${e.message}`);
    }
  }
  if (task.response) {
    try {
      task.response.data.destroy();
    } catch (e) {
      logger.warn(`关闭响应流失败: ${e.message}`);
    }
  }

  downloadTasks.delete(id);
  logger.info(`任务已删除: id=${id}`);
}

// 暂停下载
export function pauseDownload(id) {
  logger.info(`暂停下载: id=${id}`);
  const task = downloadTasks.get(id);
  if (!task || task.state !== 'progress') {
    logger.warn(`无法暂停任务: id=${id}, state=${task ? task.state : '任务不存在'}`);
    return { success: false };
  }

  task.state = 'paused';
  if (task.speedInterval) clearInterval(task.speedInterval);
  if (task.response && task.response.data) {
    try {
      task.response.data.destroy(); // 中断连接
    } catch (e) {
      logger.warn(`中断连接失败: ${e.message}`);
    }
  }

  return { success: true };
}

// 继续下载（重新调用 createDownload）
export async function resumeDownload(id, mainWindow) {
  logger.info(`=== 开始 resumeDownload ===`);
  logger.info(`resumeDownload 参数: id=${id}`);
  
  const task = downloadTasks.get(id);
  logger.info(`获取任务: ${task ? '成功' : '失败'}`);
  
  if (!task) {
    logger.warn(`任务不存在: id=${id}`);
    return { success: false, error: '任务不存在' };
  }
  
  logger.info(`任务状态: ${task.state}`);
  if (task.state !== 'paused') {
    logger.warn(`任务状态不是暂停状态: ${task.state}`);
    return { success: false, error: '任务未处于暂停状态' };
  }
  
  // 关键修改：在重新创建下载前，先从任务列表中移除旧任务
  logger.info(`从任务列表中移除旧任务: id=${id}`);
  downloadTasks.delete(id);
  
  logger.info(`准备调用 createDownload: url=${task.url}, savePath=${task.savePath}`);
  // 重新开始（会自动断点续传）
  const result = await createDownload(id, task.url, task.softName, task.savePath, mainWindow);
  logger.info(`createDownload 返回结果:`, result);
  logger.info(`=== 结束 resumeDownload ===`);
  return result;
}

// 取消下载
export function cancelDownload(id) {
  logger.info(`取消下载: id=${id}`);
  const task = downloadTasks.get(id);
  if (!task) {
    logger.warn(`任务不存在: id=${id}`);
    return { success: false };
  }

  task.state = 'cancelled';
  cleanupTask(id);

  // 删除文件
  if (task.savePath && fs.existsSync(task.savePath)) {
    try {
      fs.unlinkSync(task.savePath);
      logger.info(`已删除文件: ${task.savePath}`);
    } catch (err) {
      logger.warn(`删除文件失败: ${err.message}`);
    }
  }

  return { success: true };
}

// 导出函数
export default {
  createDownload,
  pauseDownload,
  resumeDownload,
  cancelDownload,
  downloadTasks
};